package com.hz.foodstalls.weixin.controller;

import com.hz.foodstalls.config.Constant;
import com.hz.foodstalls.model.WechatRobot;
import com.hz.foodstalls.model.WechatRobotMedia;
import com.hz.foodstalls.model.WexinMsg;
import com.hz.foodstalls.model.WxUser;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.log.Log;
import com.jfinal.weixin.iot.msg.InEquDataMsg;
import com.jfinal.weixin.iot.msg.InEqubindEvent;
import com.jfinal.weixin.sdk.jfinal.MsgController;
import com.jfinal.weixin.sdk.msg.in.*;
import com.jfinal.weixin.sdk.msg.in.card.*;
import com.jfinal.weixin.sdk.msg.in.event.*;
import com.jfinal.weixin.sdk.msg.in.speech_recognition.InSpeechRecognitionResults;
import com.jfinal.weixin.sdk.msg.out.OutMsg;
import com.jfinal.weixin.sdk.msg.out.OutTextMsg;

import java.util.List;
import java.util.Map;

@ControllerBind(controllerKey = "/msg")
public class WeixinMsgController extends MsgController {
    private static final String helpStr = "\t你的品位不错哦  么么哒。";
    static Log logger = Log.getLog(WeixinMsgController.class);

    /**
     * 如果要支持多公众账号，只需要在此返回各个公众号对应的 ApiConfig 对象即可 可以通过在请求 url 中挂参数来动态从数据库中获取
     * ApiConfig 属性值
     */
    // public ApiConfig getApiConfig() {
    // String appid = getPara("appid", "默认的appid");
    // ApiConfig ac = ApiConfigKit.getApiConfig(appid);
    //
    // // 配置微信 API 相关常量
    // ac.setToken(PropKit.get("token"));
    // ac.setAppId(PropKit.get("appId"));
    // ac.setAppSecret(PropKit.get("appSecret"));
    //
    // /**
    // * 是否对消息进行加密，对应于微信平台的消息加解密方式： 1：true进行加密且必须配置 encodingAesKey
    // * 2：false采用明文模式，同时也支持混合模式
    // */
    // ac.setEncryptMessage(PropKit.getBoolean("encryptMessage", false));
    // ac.setEncodingAesKey(PropKit.get("encodingAesKey", "setting it in config
    // file"));
    // return ac;
    // }
    protected void processInTextMsg(InTextMsg inTextMsg) {
        WexinMsg.dao.saveWxMag(inTextMsg);
        String content = inTextMsg.getContent();
        String appid = getPara("appId");
        // 取关键字map
        Map<Integer, String> map = WechatRobot.dao.getKeyWords(appid);
        // 未命中取默认回复
        OutMsg outmsg = WechatRobotMedia.dao.buildOutMessage(WechatRobot.dao.getdefault(appid), inTextMsg);
        outmsg = getOutMsg(inTextMsg, content, map, outmsg);
        render(outmsg);
    }

    //判断是否匹配，如匹配则返回对应的msg
    private OutMsg getOutMsg(InMsg inTextMsg, String content, Map<Integer, String> map, OutMsg outmsg) {
        boolean a;
        for (Map.Entry<Integer, String> entry : map.entrySet()) {
            a = content.contains(entry.getValue());
            if (a == true) {
                int wrid = entry.getKey();
                // 构造outmsg
                List<WechatRobotMedia> wrms = WechatRobotMedia.dao
                        .find("select * from wechat_robot_media where wechat_robot_id = ? ", wrid);
                outmsg = WechatRobotMedia.dao.buildOutMessage(wrms, inTextMsg);
                break;
            }
        }
        return outmsg;
    }

    @Override
    protected void processInVoiceMsg(InVoiceMsg inVoiceMsg) {
        String appid = getPara("appId");
        OutMsg outmsg = WechatRobotMedia.dao.buildOutMessage(WechatRobot.dao.getdefault(appid), inVoiceMsg);
        render(outmsg);
    }

    @Override
    protected void processInVideoMsg(InVideoMsg inVideoMsg) {
        /*
         * 腾讯 api 有 bug，无法回复视频消息，暂时回复文本消息代码测试 OutVideoMsg outMsg = new
         * OutVideoMsg(inVideoMsg); outMsg.setTitle("OutVideoMsg 发送");
         * outMsg.setDescription("刚刚发来的视频再发回去"); // 将刚发过来的视频再发回去，经测试证明是腾讯官方的 api
         * 有 bug，待 api bug 却除后再试 outMsg.setMediaId(inVideoMsg.getMediaId());
         * render(outMsg);
         */
        String appid = getPara("appId");
        OutMsg outmsg = WechatRobotMedia.dao.buildOutMessage(WechatRobot.dao.getdefault(appid), inVideoMsg);
        render(outmsg);
    }

    @Override
    protected void processInShortVideoMsg(InShortVideoMsg inShortVideoMsg) {
        String appid = getPara("appId");
        OutMsg outmsg = WechatRobotMedia.dao.buildOutMessage(WechatRobot.dao.getdefault(appid), inShortVideoMsg);
        render(outmsg);
    }

    @Override
    protected void processInLocationMsg(InLocationMsg inLocationMsg) {
        String appid = getPara("appId");
        OutMsg outmsg = WechatRobotMedia.dao.buildOutMessage(WechatRobot.dao.getdefault(appid), inLocationMsg);
        render(outmsg);
    }

    @Override
    protected void processInLinkMsg(InLinkMsg inLinkMsg) {
        String appid = getPara("appId");
        OutMsg outmsg = WechatRobotMedia.dao.buildOutMessage(WechatRobot.dao.getdefault(appid), inLinkMsg);
        render(outmsg);
    }

    @Override
    protected void processInCustomEvent(InCustomEvent inCustomEvent) {
        renderNull();
    }

    protected void processInImageMsg(InImageMsg inImageMsg) {
        String appid = getPara("appId");
        OutMsg outmsg = WechatRobotMedia.dao.buildOutMessage(WechatRobot.dao.getdefault(appid), inImageMsg);
        render(outmsg);
    }

    /**
     * 实现父类抽方法，处理关注/取消关注消息
     */
    protected void processInFollowEvent(InFollowEvent inFollowEvent) {
        if (InFollowEvent.EVENT_INFOLLOW_SUBSCRIBE.equals(inFollowEvent.getEvent())) {
            WxUser.dao.saveWxUser(inFollowEvent.getFromUserName(), getPara("appId"));
            String appid = getPara("appId");
            OutMsg outMsg = WechatRobotMedia.dao.buildOutMessage(WechatRobot.dao.getMediaByType(appid, Constant.WECHAT_ROBOT_SUBSCRIBE), inFollowEvent);
            render(outMsg);
        }
        // 如果为取消关注事件，将无法接收到传回的信息
        if (InFollowEvent.EVENT_INFOLLOW_UNSUBSCRIBE.equals(inFollowEvent.getEvent())) {
            WxUser.dao.deleteByOpenId(inFollowEvent.getFromUserName());
        }
    }

    @Override
    protected void processInQrCodeEvent(InQrCodeEvent inQrCodeEvent) {
        System.out.println("扫码.......");
        if (InQrCodeEvent.EVENT_INQRCODE_SUBSCRIBE.equals(inQrCodeEvent.getEvent())) {
            logger.debug("扫码未关注：" + inQrCodeEvent.getFromUserName());
            OutTextMsg outMsg = new OutTextMsg(inQrCodeEvent);
            outMsg.setContent("感谢您的关注，二维码内容：" + inQrCodeEvent.getEventKey());
            render(outMsg);
        }
        if (InQrCodeEvent.EVENT_INQRCODE_SCAN.equals(inQrCodeEvent.getEvent())) {
            logger.debug("扫码已关注：" + inQrCodeEvent.getFromUserName());
            renderOutTextMsg("扫码已关注,二维码内容：" + inQrCodeEvent.getEventKey());
        }

    }

    @Override
    protected void processInLocationEvent(InLocationEvent inLocationEvent) {
        logger.debug("发送地理位置事件：" + inLocationEvent.getFromUserName());
        OutTextMsg outMsg = new OutTextMsg(inLocationEvent);
        outMsg.setContent("地理位置是：" + inLocationEvent.getLatitude());
        render(outMsg);
    }

    @Override
    protected void processInMassEvent(InMassEvent inMassEvent) {
        logger.debug("测试方法：processInMassEvent()");
        renderNull();
    }

    /**
     * 实现父类抽方法，处理自定义菜单事件
     */
    protected void processInMenuEvent(InMenuEvent inMenuEvent) {
        logger.debug("菜单事件：" + inMenuEvent.getFromUserName());
        OutTextMsg outMsg = new OutTextMsg(inMenuEvent);
        outMsg.setContent("菜单事件内容是：" + inMenuEvent.getEventKey());
        render(outMsg);
    }

    @Override
    protected void processInSpeechRecognitionResults(InSpeechRecognitionResults inSpeechRecognitionResults) {
        String result = inSpeechRecognitionResults.getRecognition();
        String appid = getPara("appId");
        Map<Integer, String> map = WechatRobot.dao.getKeyWords(appid);
        // 未命中取默认回复
        OutMsg outmsg = WechatRobotMedia.dao.buildOutMessage(WechatRobot.dao.getdefault(appid),
                inSpeechRecognitionResults);
        outmsg = getOutMsg(inSpeechRecognitionResults, result, map, outmsg);
        render(outmsg);
    }

    @Override
    protected void processInTemplateMsgEvent(InTemplateMsgEvent inTemplateMsgEvent) {
        logger.debug("测试方法：processInTemplateMsgEvent()");
        renderNull();
    }

    @Override
    protected void processInPoiCheckNotifyEvent(InPoiCheckNotifyEvent arg0) {
    }

    @Override
    protected void processInShakearoundUserShakeEvent(InShakearoundUserShakeEvent arg0) {
    }

    @Override
    protected void processInVerifyFailEvent(InVerifyFailEvent arg0) {
    }

    @Override
    protected void processInVerifySuccessEvent(InVerifySuccessEvent arg0) {
    }

    @Override
    protected void processInWifiEvent(InWifiEvent inWifiEvent) {
    }

    @Override
    protected void processInUserCardEvent(InUserCardEvent inUserCardEvent) {
    }

    @Override
    protected void processInUpdateMemberCardEvent(InUpdateMemberCardEvent inUpdateMemberCardEvent) {
    }

    @Override
    protected void processInUserPayFromCardEvent(InUserPayFromCardEvent inUserPayFromCardEvent) {
    }

    @Override
    protected void processInMerChantOrderEvent(InMerChantOrderEvent inMerChantOrderEvent) {
    }

    @Override
    protected void processIsNotDefinedEvent(InNotDefinedEvent inNotDefinedEvent) {
    }

    @Override
    protected void processIsNotDefinedMsg(InNotDefinedMsg inNotDefinedMsg) {
    }

    @Override
    protected void processInUserGiftingCardEvent(InUserGiftingCardEvent msg) {
    }

    @Override
    protected void processInUserGetCardEvent(InUserGetCardEvent msg) {
    }

    @Override
    protected void processInUserConsumeCardEvent(InUserConsumeCardEvent msg) {
    }

    @Override
    protected void processInCardSkuRemindEvent(InCardSkuRemindEvent msg) {
    }

    @Override
    protected void processInCardPayOrderEvent(InCardPayOrderEvent msg) {
    }

    @Override
    protected void processInCardPassCheckEvent(InCardPassCheckEvent msg) {
    }

    @Override
    protected void processInEqubindEvent(InEqubindEvent msg) {
    }

    @Override
    protected void processInEquDataMsg(InEquDataMsg msg) {
    }

}
